package cn.cloud.all.security.access.event;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationListener;

public class LoggerListener implements ApplicationListener<AbstractAuthorizationEvent> {

    private static final Log logger = LogFactory.getLog(LoggerListener.class);

    public void onApplicationEvent(AbstractAuthorizationEvent event) {
        if (event instanceof AuthenticationCredentialsNotFoundEvent) {
            AuthenticationCredentialsNotFoundEvent authEvent = (AuthenticationCredentialsNotFoundEvent) event;

            if (logger.isWarnEnabled()) {
                logger.warn("Security interception failed due to: "
                        + authEvent.getCredentialsNotFoundException()
                        + "; secure object: " + authEvent.getSource()
                        + "; configuration attributes: "
                        + authEvent.getConfigAttributes());
            }
        }

        if (event instanceof AuthorizationFailureEvent) {
            AuthorizationFailureEvent authEvent = (AuthorizationFailureEvent) event;

            if (logger.isWarnEnabled()) {
                logger.warn("Security authorization failed due to: "
                        + authEvent.getAccessDeniedException()
                        + "; authenticated principal: " + authEvent.getAuthentication()
                        + "; secure object: " + authEvent.getSource()
                        + "; configuration attributes: "
                        + authEvent.getConfigAttributes());
            }
        }

        if (event instanceof AuthorizedEvent) {
            AuthorizedEvent authEvent = (AuthorizedEvent) event;

            if (logger.isInfoEnabled()) {
                logger.info("Security authorized for authenticated principal: "
                        + authEvent.getAuthentication() + "; secure object: "
                        + authEvent.getSource() + "; configuration attributes: "
                        + authEvent.getConfigAttributes());
            }
        }

        if (event instanceof PublicInvocationEvent) {
            PublicInvocationEvent authEvent = (PublicInvocationEvent) event;
            if (logger.isInfoEnabled()) {
                logger.info("Security interception not required for public secure object: " + authEvent.getSource());
            }
        }
    }
}
